package com.hand.demo.app.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hand.demo.app.service.*;
import com.hand.demo.domain.dto.ResumeDTO;
import com.hand.demo.domain.entity.*;
import io.choerodon.core.domain.Page;
import io.choerodon.core.exception.CommonException;
import io.choerodon.mybatis.domain.AuditDomain;
import io.choerodon.mybatis.pagehelper.PageHelper;
import io.choerodon.mybatis.pagehelper.domain.PageRequest;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.hand.demo.domain.repository.HhrTaBasicInfoRepository;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 简历基本信息解析表(HhrTaBasicInfo)应用服务
 *
 * @author
 * @since 2025-06-16 12:16:55
 */
@Service
public class HhrTaBasicInfoServiceImpl implements HhrTaBasicInfoService {

    final static Logger log = LoggerFactory.getLogger(HhrTaBasicInfoServiceImpl.class);
    @Autowired
    private HhrTaBasicInfoRepository hhrTaBasicInfoRepository;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private HhrTaCertService hhrTaCertService;

    @Autowired
    private HhrTaEducationService hhrTaEducationService;

    @Autowired
    private HhrTaJobExpService hhrTaJobExpService;

    @Autowired
    private HhrTaLangService hhrTaLangService;

    @Autowired
    private HhrTaProjExpService hhrTaProjExpService;

    @Autowired
    private HhrTaSkillsService hhrTaSkillsService;

    @Autowired
    private HhrTaSocialExpService hhrTaSocialExpService;

    @Autowired
    private HhrTaTrainingService hhrTaTrainingService;


    @Override
    public Page<HhrTaBasicInfo> selectList(PageRequest pageRequest, HhrTaBasicInfo hhrTaBasicInfo) {
        return PageHelper.doPageAndSort(pageRequest, () -> hhrTaBasicInfoRepository.selectList(hhrTaBasicInfo));
    }

    @Override
    public void saveData(List<HhrTaBasicInfo> hhrTaBasicInfos) {
        List<HhrTaBasicInfo> insertList = hhrTaBasicInfos.stream().filter(line -> line.getId() == null).collect(Collectors.toList());
        List<HhrTaBasicInfo> updateList = hhrTaBasicInfos.stream().filter(line -> line.getId() != null).collect(Collectors.toList());
        hhrTaBasicInfoRepository.batchInsertSelective(insertList);
        hhrTaBasicInfoRepository.batchUpdateByPrimaryKeySelective(updateList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void parseAndSaveResume(String resumeJson, Long organizationId) {
        try {
            // 将json串反序列化为java对象
            ResumeDTO resumeDTO = objectMapper.readValue(resumeJson, ResumeDTO.class);
            log.info("resumeDTO : {}", resumeDTO);
            HhrTaBasicInfo basicInfo = resumeDTO.getBasicInfo();
            if(basicInfo == null) {
                throw new CommonException("基本信息不能为空");
            }
                basicInfo.setTenantId(organizationId);
                // 判断是否是同一个人的简历
                HhrTaBasicInfo query = new HhrTaBasicInfo();
                query.setName(basicInfo.getName());
                query.setPhone(basicInfo.getPhone());
                query.setEmail(basicInfo.getEmail());
                query.setTenantId(basicInfo.getTenantId());
                List<HhrTaBasicInfo> existingResumes = hhrTaBasicInfoRepository.select(query);
                Long resumeId;
                if (!existingResumes.isEmpty()) {
                    // 已存在简历，更新基本信息
                    HhrTaBasicInfo existingResume = existingResumes.get(0);
                    BeanUtils.copyProperties(basicInfo, existingResume, "id",
                            AuditDomain.FIELD_OBJECT_VERSION_NUMBER, AuditDomain.FIELD_CREATED_BY); // 保留原ID
                    hhrTaBasicInfoRepository.updateByPrimaryKeySelective(existingResume);
                    resumeId = existingResume.getId();
                } else {
                    // 不存在简历 直接插入
                    hhrTaBasicInfoRepository.insert(basicInfo);
                    resumeId = basicInfo.getId(); // 获取生成的ID
                }
                // 保存证书 多条信息
                List<HhrTaCert> certList = resumeDTO.getCert();
                if (CollectionUtils.isNotEmpty(certList)) {
                    // 如果是更新操作，先删除旧数据再插入新数据 保证数据的一致性
                    if(!existingResumes.isEmpty()) {
                        hhrTaCertService.deleteByResumeId(resumeId);
                    }
                    certList.forEach(item -> item.setTenantId(organizationId));
                    certList.forEach(item -> item.setResumeId(resumeId));
                    hhrTaCertService.saveData(certList);
                }

                //  保存教育经历 多条信息
                List<HhrTaEducation> educationList = resumeDTO.getEducation();
                if (CollectionUtils.isNotEmpty(educationList)) {
                    if (!existingResumes.isEmpty()) {
                        hhrTaEducationService.deleteByResumeId(resumeId);
                    }
                    educationList.forEach(item -> item.setTenantId(organizationId));
                    educationList.forEach(item -> item.setResumeId(resumeId));
                    hhrTaEducationService.saveData(educationList);
                }

                // 保存工作经历及实习经历 多条信息
                List<HhrTaJobExp> jobExpList = resumeDTO.getJobExp();
                if (CollectionUtils.isNotEmpty(jobExpList)) {
                    if (!existingResumes.isEmpty()) {
                        hhrTaJobExpService.deleteByResumeId(resumeId);
                    }
                    jobExpList.forEach(item -> item.setTenantId(organizationId));
                    jobExpList.forEach(item -> item.setResumeId(resumeId));
                    hhrTaJobExpService.saveData(jobExpList);
                }

                // 保存语言证书经历 多条信息
                List<HhrTaLang> langList = resumeDTO.getLang();
                if (CollectionUtils.isNotEmpty(langList)) {
                    if (!existingResumes.isEmpty()) {
                        hhrTaLangService.deleteByResumeId(resumeId);
                    }
                    langList.forEach(item -> item.setTenantId(organizationId));
                    langList.forEach(item -> item.setResumeId(resumeId));
                    hhrTaLangService.saveData(langList);
                }

                // 保存项目经历 信息 多条信息
                List<HhrTaProjExp> projExpList = resumeDTO.getProjExp();
                if (CollectionUtils.isNotEmpty(projExpList)) {
                    if (!existingResumes.isEmpty()) {
                        hhrTaProjExpService.deleteByResumeId(resumeId);
                    }
                    projExpList.forEach(item -> item.setTenantId(organizationId));
                    projExpList.forEach(item -> item.setResumeId(resumeId));
                    hhrTaProjExpService.saveData(projExpList);
                }

                List<HhrTaSkills> skillsList = resumeDTO.getSkills();
                if (CollectionUtils.isNotEmpty(projExpList)) {
                    if (!existingResumes.isEmpty()) {
                        hhrTaSkillsService.deleteByResumeId(resumeId);
                    }
                    skillsList.forEach(item -> item.setTenantId(organizationId));
                    skillsList.forEach(item -> item.setResumeId(resumeId));
                    hhrTaSkillsService.saveData(skillsList);
                }

                List<HhrTaSocialExp> socialExpList = resumeDTO.getSocialExp();
                if (CollectionUtils.isNotEmpty(socialExpList)) {
                    if (!existingResumes.isEmpty()) {
                        hhrTaSocialExpService.deleteByResumeId(resumeId);
                    }
                    socialExpList.forEach(item -> item.setTenantId(organizationId));
                    socialExpList.forEach(item -> item.setResumeId(resumeId));
                    hhrTaSocialExpService.saveData(socialExpList);
                }
                List<HhrTaTraining> taTrainingList = resumeDTO.getTraining();
                if (CollectionUtils.isNotEmpty(taTrainingList)) {
                    if (!existingResumes.isEmpty()) {
                       hhrTaTrainingService.deleteByResumeId(resumeId);
                    }
                    taTrainingList.forEach(item -> item.setTenantId(organizationId));
                    taTrainingList.forEach(item -> item.setResumeId(resumeId));
                    hhrTaTrainingService.saveData(taTrainingList);
                }
        } catch (JsonProcessingException e) {
            log.error("简历解析失败:{}", e);
            throw new RuntimeException("JSON解析失败", e);
        }
    }
}

